<template>
  <div class="box">
    <div class="container">
      <van-form @submit="onSubmit">
        <div v-for="(item,index) in formList" class="form_item">
          <van-field
            v-model="formAction[index].value"
            v-if="['input','select','cascader'].includes(item.type)"
            :style="{order:item.formId}"
            :clickable="['select'].includes(item.type)"
            :readonly="['select','cascader'].includes(item.type)"
            :is-link="['cascader'].includes(item.type)"
            :name="item.name"
            :label="item.name"
            :placeholder="item.placeholder"
            @click="item.type == 'select' && showPickerFn(index,item.config);item.type == 'cascader' && showCasFn(index,item.config)"
            :rules="[{ required: item.required == '1', message: '请填写' + item.name },{validator:value=>{return ['input'].includes(item.type)? (value.length<=item.config.maxlength && value.length>=item.config.minlength) : true},message: `请输入${item.config.minlength}-${item.config.maxlength}个字段`}]"
          />
          <van-field
            v-if="['file'].includes(item.type)"
            :name="item.name"
            :label="item.name"
            :rules="[{ required: item.required == '1', message: '请填写' + item.name }]"
            @click="setFileConfig(index,item.config)"
          >
            <template #input>
              <van-uploader
                v-model="uploader[index]"
                multiple
                :accept="item.config.type+'/*'"
                :max-size="Number(item.config.maximum) * 1024 * 1024"
                :max-count="1"
                @oversize="onOversize"
                :before-read="beforeRead"
                :after-read="afterRead"
              />
              <div class="fileHolder">{{item.placeholder}}</div>
            </template>
          </van-field>
        </div>
        <div class="stepBox flex" v-if="isFree == '1'" style="margin-top: 10px">
          <span>数量</span>
          <van-stepper v-model="count"/>
        </div>
        <div class="stepBox flex" v-if="isFree == '1'">
          <span>单价</span>
          <span>￥<i style="font-size: 18px;font-style: inherit">{{ unitPrice }}</i></span>
        </div>
        <!--表单提交-->
        <van-submit-bar
          :price="totalFee"
          :disabled="submitFlag"
          button-text="提交信息"
          native-type="submit"
        />
      </van-form>
    </div>
    <!--下拉选弹窗-->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!--级联弹窗-->
    <van-popup v-model="showCas" round position="bottom">
      <van-cascader
        :options="options"
        :field-names="fieldNames"
        @close="showCas = false"
        @finish="onFinish"
      />
    </van-popup>
    <div class="footer"></div>
  </div>
</template>

<script>
import areaList from '../assets/js/Area'
import { Toast } from 'vant';
import {mapState} from 'vuex'
export default {
  name: 'Information',
  data () {
    return {
      activityId:0,
      showCas:false,
      showPicker:false,
      casIndex: 0,
      pickerIndex: 0,
      fileIndex: 0,
      fileRules:{},
      options: [],
      columns: [],
      uploader: [],
      fieldNames: {
        text: 'label',
        value: 'label',
        children: 'children',
      },
      isFree: '',
      count: 1,
      submitFlag:false,
      priceIndex:0,
      unitPrice: 0,
      formList:[],
      formAction:[],
      areaList: areaList // 数据格式见 Area 组件文档
    }
  },
  created () {
    // 类型转换
    this.count = +this.$route.query.count
    this.activityId = +this.$route.query.activityId
    this.priceIndex = +this.$route.query.priceIndex
    this.isFree = this.$route.query.isFree
    this.unitPrice = Number(this.$route.query.unitPrice).toFixed(2)
    this.getActForm()
  },
  computed: {
    ...mapState(['priceList']),
    totalFee () {
      return this.unitPrice * this.count * 100 || 0
    }
  },
  methods: {
    getActForm(){
      this.$http.post('/actForm/findByActivityId', this.activityId).then(res=>{
        if(res && res.state == '200'){
          this.formList = res.data
          this.formList.map((item,index)=>{
            item.config = JSON.parse(item.config)
            this.formAction.push({
              formId:item.formId,
              type:item.type,
              name:item.name,
              value:''
            })
            this.uploader.push([])
          })
        }else{
          this.$toast(res.message)
        }
      }).catch(error=>{})
    },
    showCasFn(index,config){
      this.showCas =true
      this.options = config.option
      this.casIndex = index
    },
    showPickerFn(index,config){
      this.showPicker = true;
      let options = []
      config.option.forEach(o=>{
        options.push(o.value)
      })
      this.columns = options
      this.pickerIndex = index
    },
    onFinish({ selectedOptions }){
      this.showCas = false;
      this.formAction[this.casIndex].value = selectedOptions.map((option) => option.label).join('/');
    },
    onConfirm(value) {
      this.showPicker = false;
      this.formAction[this.pickerIndex].value = value;
    },
    //设置校验规则
    setFileConfig(index,config){
      this.fileIndex = index
      this.fileRules = config
    },
    onOversize() {
      Toast('文件大小不能超过 ' + this.fileRules.maximum + 'M');
    },
    //文件上传前置处理
    beforeRead(file) {
      console.log(file)
      const fileType = file.type.split('/')[0]
      if(fileType !== this.fileRules.type){
        this.$toast('请上传正确格式的文件');
        return false;
      }
      // const format = this.fileRules.format.map(f=>{
      //   return this.fileRules.type + '/' + f.toLowerCase();
      // })
      // if (!format.includes(file.type)) {
      //   this.$toast('请上传 '+this.fileRules.format.join('/')+' 格式');
      //   return false;
      // }
      return true;
    },
    afterRead(file) {
      this.submitFlag = true
      let data = new FormData();
      data.append('file', file.file);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.$http.post('/common/upload', data,config).then(res=>{
          if (res && res.state == '200') {
            this.formAction[this.fileIndex].value = res.data.actFileRes
            this.submitFlag = false
          }else {
            this.$toast(res.message)
          }
      })
    },
    onSubmit () {
      Toast.loading({
        message: '资料提交中...',
        duration: 0,
        forbidClick: true,
        loadingType: 'spinner',
      });
      let params = {
        activityId:this.activityId,
        form:this.formAction,
        order:{
          count:this.count,
          price:this.priceList[this.priceIndex]
        }
      }
      this.$http.post('/actEnroll/submitForm', params).then(res=>{
          if (res && res.state == '200') {
            Toast.clear();
            this.$router.push('/PayInfo?orderId='+res.data.orderId)
          }else {
            Toast.clear();
            this.$toast(res.message)
          }
      })
    },
  }
}
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.box .container {
  flex: 1 1 auto;
  background-color: #f1f1f1;
  .van-form{
    display: flex;
    flex-direction: column;
  }
}

.box .footer {
  height: 55px;
  width: 100%;
  flex-shrink: 0;
  display: flex;
}
.van-form .form_item{
  border-bottom: 1px solid #f1f1f1;
}

.stepBox {
  background-color: #fff;
  padding: 15px;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/ .van-field--error .van-field__control, .van-field--error .van-field__control::placeholder{
  color: #999!important;
}
/deep/ .van-field__control{
  flex-direction: column;
  align-items: flex-start;
  .fileHolder{
    color: #666;
  }
}
</style>
